<?php


namespace App\Common;

class General
{
    private static $data;

    private function __construct()
    {
    }

    public static function get($key)
    {
        return self::$data[$key];
    }

    public static function set($key, $value)
    {
        if (isset(self::$data[$key])) {
            trigger_error("General `$key` already exist.", E_USER_ERROR);
        }
        self::$data[$key] = $value;
    }

    public static function interrupt(string $msg, int $code = 500)
    {
        header("HTTP/1.1 $code");
        exit($msg);
    }

    // 组装 SQL 的 in 值
    public static function fixIn(array $arr)
    {
        $str = '';
        foreach ($arr as $v) {
            $str .= "'$v',";
        }
        return trim($str, ',');
    }

    // 读文件
    public static function readFileToArr(string $filepath, $need_cnt = false): array
    {
        $fp = fopen($filepath, 'r');
        $cnt = 0;
        $data = [];
        while ($row = fgets($fp)) {
            $cnt += 1;
            $row = trim($row);
            if ($row) {
                $data[] = ['vcRobotSerialNo' => $row];
            }
        }
        if ($need_cnt) {
            return [$data, $cnt];
        }
        return $data;
    }

    // 分割数组，批理处理
    public static function sliceBatch(array $data, callable $fn = null, int $batch = 1000)
    {
        $s = 0;
        while (true) {
            $arr = array_slice($data, $s, $batch);
            if (empty($arr)) {
                break;
            }

            if ($fn) {
                $fn($arr);
            }

            $s += $batch;
        }
    }

    public static function time2pretty($remain): string
    {
        $day = floor($remain / 86400);  //计算天
        $remain = $remain % 86400;
        $hour = floor($remain / 3600);  //计算小时
        $remain = $remain % 3600;
        $minute = floor($remain / 60);  //计算分
        $second = $remain % 60;  //剩余的秒数

        $pretty = '';
        if ($day) {
            $pretty .= "$day 天";
        }
        if ($hour) {
            $pretty .= " $hour 小时";
        }
        if ($minute) {
            $pretty .= " $minute 分";
        }
        if ($second) {
            $pretty .= " $second 秒";
        }
        return $pretty;
    }
}